package com.masterclient.app.modules.cart;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.masterclient.app.BaseFragment;
import com.eoner.common.config.Config;
import com.masterclient.app.R;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.base.FragmentHostActivity;
import com.masterclient.app.modules.cart.adapter.GatherGoodsRecyclerAdapter;
import com.masterclient.app.modules.cart.beans.GatherBean;
import com.masterclient.app.modules.cart.contract.GatherGoodsContract;
import com.masterclient.app.modules.cart.contract.GatherGoodsPresenter;
import com.masterclient.app.businessmodule.usermodule.login.index.QuickLoginActivity;
import com.eoner.baselib.utils.sp.SPUtils;
import com.masterclient.app.widget.StaggeredGoodsItemDecoration;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;

import static com.eoner.baselibrary.utils.ScreenUtils.dp2px;

/**
 * <pre>
 *     Copyright    : Copyright (c) 2020.
 *     Authour      : hxm
 *     Created Time : 2020/3/17.
 *     Desc         :
 *     Alter By     :
 * </pre>
 */
@Route(path = AroutePath.GATHER_GOODS_FRAGMENT)
public class GatherGoodsFragment extends BaseFragment<GatherGoodsPresenter> implements GatherGoodsContract.View {

    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.tv_default)
    TextView tvDefault;
    @BindView(R.id.tv_sale_volume)
    TextView tvSaleVolume;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_price_icon)
    ImageView tvPriceIcon;
    @BindView(R.id.tv_tag)
    TextView tvTag;
    @BindView(R.id.tv_des)
    TextView tvDes;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.iv_back_top)
    ImageView ivBackTop;
    @BindView(R.id.ll_activity)
    LinearLayout llActivity;

    @Autowired(name = "activityId")
    String activityId;

    private GatherGoodsRecyclerAdapter searchGoodRecyclerAdapter;
    private View footView;
    private View emptyView;
    private String sort = "new";
    private List<GatherBean.DataBean.ProductsBean> goodList;
    private int total;

    public static GatherGoodsFragment newInstance() {
        return new GatherGoodsFragment();
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_gather_goods, null);
    }

    @Override
    protected void initOnlyOnce() {
        super.initOnlyOnce();
        ARouter.getInstance().inject(this);

        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(null);
        recyclerView.addItemDecoration(new StaggeredGoodsItemDecoration(dp2px(10)));
        searchGoodRecyclerAdapter = new GatherGoodsRecyclerAdapter();
        recyclerView.setAdapter(searchGoodRecyclerAdapter);
        searchGoodRecyclerAdapter.bindToRecyclerView(recyclerView);

        footView = View.inflate(mContext, R.layout.bottom_common, null);
        emptyView = View.inflate(mContext, R.layout.null_search, null);
        ((TextView) emptyView.findViewById(R.id.tv_tip)).setText("没有找到您要的商品");
        searchGoodRecyclerAdapter.setEmptyView(emptyView);
        emptyView.setVisibility(View.GONE);

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            //用来标记是否正在向最后一个滑动
            boolean isSlidingToDown = false;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                StaggeredGridLayoutManager manager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
                int[] first = new int[manager.getSpanCount()];
                manager.findFirstCompletelyVisibleItemPositions(first);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && (first[0] == 1 || first[1] == 1)) {
                    manager.invalidateSpanAssignments();
                }

                int[] firstVisibleItemPosition = new int[manager.getSpanCount()];
                manager.findFirstVisibleItemPositions(firstVisibleItemPosition);
                if (ivBackTop != null) {
                    if (firstVisibleItemPosition[0] <= 7) {
                        ivBackTop.setVisibility(View.INVISIBLE);
                    } else {
                        ivBackTop.setVisibility(View.VISIBLE);
                    }
                }
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到顶部
                    if (!recyclerView.canScrollVertically(-1)) {
                        llActivity.setVisibility(View.VISIBLE);
                    }
                } else if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {//拖动中
                    if (llActivity.getVisibility() == View.VISIBLE) {
                        llActivity.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //dx用来判断横向滑动方向，dy用来判断纵向滑动方向
                if (dy > 0) {
                    isSlidingToDown = false;
                } else {
                    isSlidingToDown = true;
                }
            }
        });

        searchGoodRecyclerAdapter.setOnLoadMoreListener(() -> {
            if (goodList.size() < total) {
                getData(String.valueOf(goodList.size() / Integer.valueOf(PAGE_SIZE) + 1));
            }
        }, recyclerView);

        swipeLayout.setOnRefreshListener(() -> {
            getGoodsFirstPage();
        });
        getGoodsFirstPage();
    }

    @OnClick({R.id.fl_back, R.id.tv_default, R.id.tv_sale_volume, R.id.ll_price, R.id.iv_back_top, R.id.iv_goto_cart})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.fl_back:
                Objects.requireNonNull(getActivity()).finish();
                break;
            case R.id.tv_default:
                clickDefault();
                break;
            case R.id.tv_sale_volume:
                clickVolume();
                break;
            case R.id.ll_price:
                clickPrice();
                break;
            case R.id.iv_back_top:
                ivBackTop.setVisibility(View.GONE);
                llActivity.setVisibility(View.VISIBLE);
                recyclerView.scrollToPosition(0);
                break;
            case R.id.iv_goto_cart:
                if (!TextUtils.isEmpty(SPUtils.getInstance().getString(Config.CUSTOMERID))) {
                    Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.SHOP_CART_FRAGMENT)
                            .withString("from", "activity")
                            .navigation();
                    FragmentHostActivity.openFragment(getActivity(), fragment);
                } else {
                    this.startActivity(new Intent(getActivity(), QuickLoginActivity.class));
                }
                break;
        }
    }

    /**
     * 切换品牌
     */
    private void getGoodsFirstPage() {
        ivBackTop.setVisibility(View.GONE);
        if (goodList != null) {
            goodList.clear();
            emptyView.setVisibility(View.GONE);
            searchGoodRecyclerAdapter.notifyDataSetChanged();
        }
        searchGoodRecyclerAdapter.setEnableLoadMore(true);

        if ("new".equals(sort)) {

        } else if ("hot".equals(sort)) {
            tvDefault.setTextColor(getResources().getColor(R.color.color_333333));
            tvSaleVolume.setTextColor(getResources().getColor(R.color.textColor_999));
            sort = "new";
        } else if ("price_desc".equals(sort) || "price_asc".equals(sort)) {
            tvDefault.setTextColor(getResources().getColor(R.color.color_333333));
            tvSaleVolume.setTextColor(getResources().getColor(R.color.textColor_999));
            tvPriceIcon.setImageResource(R.mipmap.paixu_icon);
            tvPrice.setTextColor(getResources().getColor(R.color.textColor_999));
            sort = "new";
        }
        getData("1");
    }

    private void clickDefault() {
        if ("new".equals(sort)) {

        } else if ("hot".equals(sort)) {
            tvDefault.setTextColor(getResources().getColor(R.color.color_333333));
            tvSaleVolume.setTextColor(getResources().getColor(R.color.textColor_999));
            sort = "new";
            searchNewCondition();
        } else if ("price_desc".equals(sort) || "price_asc".equals(sort)) {
            tvDefault.setTextColor(getResources().getColor(R.color.color_333333));
            tvSaleVolume.setTextColor(getResources().getColor(R.color.textColor_999));
            tvPriceIcon.setImageResource(R.mipmap.paixu_icon);
            tvPrice.setTextColor(getResources().getColor(R.color.textColor_999));
            sort = "new";
            searchNewCondition();
        }
    }

    private void clickVolume() {
        if ("new".equals(sort)) {
            tvSaleVolume.setTextColor(getResources().getColor(R.color.color_333333));
            tvDefault.setTextColor(getResources().getColor(R.color.textColor_999));
            sort = "hot";
            searchNewCondition();
        } else if ("hot".equals(sort)) {

        } else if ("price_desc".equals(sort) || "price_asc".equals(sort)) {
            tvPriceIcon.setImageResource(R.mipmap.paixu_icon);
            tvSaleVolume.setTextColor(getResources().getColor(R.color.color_333333));
            tvPrice.setTextColor(getResources().getColor(R.color.textColor_999));
            sort = "hot";
            searchNewCondition();
        }
    }

    private void clickPrice() {
        if ("new".equals(sort)) {
            sort = "price_desc";
            tvSaleVolume.setTextColor(getResources().getColor(R.color.textColor_999));
            tvDefault.setTextColor(getResources().getColor(R.color.textColor_999));
            tvPriceIcon.setImageResource(R.mipmap.paixu_down_icon);
            tvPrice.setTextColor(getResources().getColor(R.color.color_333333));
        } else if ("hot".equals(sort)) {
            sort = "price_desc";
            tvSaleVolume.setTextColor(getResources().getColor(R.color.textColor_999));
            tvDefault.setTextColor(getResources().getColor(R.color.textColor_999));
            tvPriceIcon.setImageResource(R.mipmap.paixu_down_icon);
            tvPrice.setTextColor(getResources().getColor(R.color.color_333333));
        } else if ("price_desc".equals(sort)) {
            sort = "price_asc";
            tvPriceIcon.setImageResource(R.mipmap.paixu_top_icon);
        } else if ("price_asc".equals(sort)) {
            sort = "price_desc";
            tvPriceIcon.setImageResource(R.mipmap.paixu_down_icon);
        }
        searchNewCondition();
    }

    private void searchNewCondition() {
        if (goodList != null) {
            goodList.clear();
            emptyView.setVisibility(View.GONE);
            searchGoodRecyclerAdapter.notifyDataSetChanged();
        }
        recyclerView.scrollToPosition(0);
        footView.setVisibility(View.GONE);
        getData("1");
    }

    public void getData(String page) {
        if (mPresenter == null) return;
        mPresenter.getGatherGoodsList(page, PAGE_SIZE, activityId, sort);
    }

    @Override
    public void showGatherGoodsList(GatherBean gatherBean) {
        if (swipeLayout.isRefreshing()) {
            swipeLayout.setRefreshing(false);
        }

        if (gatherBean.data != null) {
            //活动栏展示
            if (!TextUtils.isEmpty(gatherBean.data.activityName)) {
                llActivity.setVisibility(View.VISIBLE);
                tvTag.setText(gatherBean.data.labelName);
                tvDes.setText(gatherBean.data.activityName);
            } else {
                llActivity.setVisibility(View.GONE);
            }

            if ("1".equals(gatherBean.data.page) && gatherBean.data.products.size() == 0) {
                showGatherGoodsListFailed("");
            } else {
                if (goodList == null) {
                    goodList = new ArrayList<>();
                }
                goodList.addAll(gatherBean.data.products);
            }
        }

        total = Integer.valueOf(gatherBean.data.total);
        if (goodList.size() <= 20) {
            searchGoodRecyclerAdapter.setNewData(goodList);
        } else {
            searchGoodRecyclerAdapter.notifyItemRangeInserted(goodList.size() - gatherBean.data.products.size(), gatherBean.data.products.size());
            searchGoodRecyclerAdapter.loadMoreComplete();
        }

        if (goodList.size() >= total) {
            searchGoodRecyclerAdapter.setEnableLoadMore(false);
            searchGoodRecyclerAdapter.setFooterView(footView);
            footView.setVisibility(View.VISIBLE);
        } else {
            footView.setVisibility(View.GONE);
        }
    }

    @Override
    public void showGatherGoodsListFailed(String msg) {
        if (swipeLayout != null) {
            swipeLayout.setRefreshing(false);
        }
        emptyView.setVisibility(View.VISIBLE);
    }
}
